import type { AccountLoginReq, AuthType, EmailLoginReq, PhoneLoginReq } from '@/apis/auth'
import { accountLogin, emailLogin, getUserInfo, phoneLogin, socialLogin } from '@/apis/auth'
import { useUserStore } from '@/store/user'
import { defineStore } from 'pinia'
import { computed } from 'vue'

interface AuthInfo {
  token?: string
  roles?: string[]
  permissions?: string[]
}

const initValues: AuthInfo = {
  token: null,
  roles: [],
  permissions: [],
}

// 通用登录参数处理函数
function createLoginParams(params: any, authType: AuthType) {
  return {
    ...params,
    authType,
    clientId: import.meta.env.VITE_CLIENT_ID,
  }
}

// 登录函数映射
const loginApiMap: Record<AuthType, (params: any) => Promise<any>> = {
  ACCOUNT: (params: any) =>
    accountLogin(
      createLoginParams(params, 'ACCOUNT') as AccountLoginReq,
    ),
  EMAIL: (params: any) =>
    emailLogin(
      createLoginParams(params, 'EMAIL') as EmailLoginReq,
    ),
  PHONE: (params: any) =>
    phoneLogin(
      createLoginParams(params, 'PHONE') as PhoneLoginReq,
    ),
  SOCIAL: (params: any) =>
    socialLogin(createLoginParams(params, 'SOCIAL')),
}

function storeSetup() {
  const authInfo = reactive<AuthInfo>(initValues)
  const userStore = useUserStore()

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   * @param type 登录类型：'ACCOUNT' | 'EMAIL' | 'PHONE' | 'SOCIAL'
   */
  async function authLogin(
    params: Record<string, any>,
    type: AuthType = 'ACCOUNT',
  ) {
    // 调用对应的登录API
    const { data } = await loginApiMap[type](params)
    const { token } = data
    if (token) {
      authInfo.token = token

      // 获取用户信息并存储到 accessStore 中
      const { data } = await getUserInfo()

      userStore.setUserInfo(data)
      authInfo.roles = data.roles
      authInfo.permissions = data.permissions
      return true
    }
    else {
      uni.showToast({
        title: data.message || '登录失败',
        icon: 'fail',
      })
      return false
    }
  }

  // 设置 token 的方法
  const setToken = (token: string) => {
    authInfo.token = token
  }

  // 清除 token 的方法
  const clearToken = () => {
    authInfo.token = undefined
  }

  // 设置 roles 的方法
  const setRoles = (roles: string[]) => {
    authInfo.roles = roles
  }

  // 清除 roles 的方法
  const clearRoles = () => {
    authInfo.roles = undefined
  }

  // 设置 permissions 的方法
  const setPermissions = (permissions: string[]) => {
    authInfo.permissions = permissions
  }

  // 清除 permissions 的方法
  const clearPermissions = () => {
    authInfo.permissions = undefined
  }

  // 一般没有 reset 需求，不需要的可以删除
  const reset = () => {
    clearPermissions()
    clearRoles()
    clearToken()
  }

  const isLogined = computed(() => !!authInfo.token)

  return {
    authLogin,
    isLogined,
    authInfo,
    reset,
    setToken,
    clearToken,
    setRoles,
    clearRoles,
    setPermissions,
    clearPermissions,
  }
}

export const useAuthStore = defineStore('auth', storeSetup, { persist: true })
